﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace APNS.NET
{
    public class NotificationPayload
    {

        public ApnsAlert AlertBody { get; set; }        
        public int? Badge { get; set; }
        public string Sound { get; set; }
        public IDictionary<string, string> CustomArguments { get; private set; }  
      
        public NotificationPayload()
        {
            CustomArguments = new Dictionary<string, string>();
        }

        public NotificationPayload(ApnsAlert alertBody)
            : base()
        {
            if (alertBody == null) 
                throw new ArgumentNullException("alertBody");
            this.AlertBody = alertBody;
        }

        public byte[] ToByteArray()
        {
            JObject jsonPayload = new JObject();
            JObject apsRoot = new JObject();
            jsonPayload["aps"] = apsRoot;

            if (AlertBody==null)
                apsRoot["alert"] = new JValue(String.Empty);
            else
                apsRoot["alert"] = AlertBody.ToJsonString();

            if (Badge.HasValue)
                apsRoot["badge"] = new JValue(Badge);
            if (!string.IsNullOrEmpty(Sound))
                apsRoot["sound"] = new JValue(Sound);

            foreach (var customArg in CustomArguments)
            {
                jsonPayload[customArg.Key] = new JValue(customArg.Value);
            }

            string jsonString = jsonPayload.ToString(Formatting.None);
            return Encoding.UTF8.GetBytes(jsonString); 
        }

    }

    
}
